package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校正手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        //保存验证码
        //session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,
                LOGIN_CODE_TTL,TimeUnit.MINUTES);
        //发送验证码
        log.debug("发送验证码成功，验证码：{}",code);

        return Result.ok();
    }

    /**
     * 实现密码登录和短信登录
     * 短信登录涉及到将验证码放在redis中
     * 密码登录就是查询数据库中的userPassword是否匹配成功
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.校正手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误");
        }
        //3.通过用户查询用户
        User user = query().eq("phone", phone).one();
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        //校验密码
         if (loginForm.getPassword() != null){
             if(!user.getPassword().equals(loginForm.getPassword())){
                 return Result.fail("密码错误");
             }
         }else if(loginForm.getPassword() == null && code == null && cacheCode != null){
             return Result.fail("验证码不能为空！");
         }else if(loginForm.getPassword() == null && code == null){
             return Result.fail("密码不能为空！");
         } else {
             //Object cacheCode = session.getAttribute("code");
             //2.校正验证码
             if(cacheCode == null||!cacheCode.equals(code)){
                 return Result.fail("验证码错误！");
             }
             //用户如果不存在就创建一个
             if(user == null){
                 user = createUserWithPhone(phone);
             }
         }
         //将登陆成功的用户信息保存在redis中
        //生成一个token
        String token = UUID.randomUUID().toString(true);
        //将user对象转换为hashmap对象
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        //储存
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        //获取用户登录信息
        Long userId = UserHolder.getUser().getId();
        //获取当前信息
        LocalDateTime dateTime = LocalDateTime.now();
        //拼接key
        String keySuffix = dateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取当天是本月的第几天
        int dayOfMonth = dateTime.getDayOfMonth();
        //写入redis
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth - 1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取用户登录信息
        Long userId = UserHolder.getUser().getId();
        //获取当前信息
        LocalDateTime dateTime = LocalDateTime.now();
        //拼接key
        String keySuffix = dateTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //获取当天是本月的第几天
        int dayOfMonth = dateTime.getDayOfMonth();
        //获取本月截止今天为止的所有的签到记录
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        Long num = result.get(0);
        if(result == null || result.isEmpty()){
            return Result.ok(0);
        }
        //循环遍历
        int count = 0;
        while(true){
            //让这个数字与1做与运算，得到数字的最后一位
             if((num & 1) == 0) {
                 //判断是否为0，说明未签到，结束
                 break;
             }else {
                 //不为0，说明已签到，计数器加1
                 count++;
             }
             num>>>= 1;
        }
        return Result.ok(count);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
